package org.icnmasjid.member.webapp.action;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.velocity.tools.generic.NumberTool;
import org.icnmasjid.member.Constants;
import org.icnmasjid.member.model.Person;
import org.icnmasjid.member.model.Role;
import org.icnmasjid.member.service.LookupManager;
import org.icnmasjid.member.service.MailEngine;
import org.icnmasjid.member.service.PersonManager;
import org.icnmasjid.member.util.CommonUtil;
import org.icnmasjid.member.util.DesEncrypter;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.MimeMailMessage;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;

public class MassParentsEmailPersonController extends BaseFormController {

	private PersonManager personManager;
	private LookupManager lookupManager;
	private MailEngine mailEngine;


    public void setPersonManager(PersonManager personManager) {
        this.personManager = personManager;
    }

    public MassParentsEmailPersonController() {
    	setCommandClass(Person.class);
    	setCommandName("person");
	}

    @Override
    protected boolean isFormSubmission(HttpServletRequest request) {
    	return true;
    }

    public ModelAndView onSubmit(HttpServletRequest request,
                                 HttpServletResponse response, Object command,
                                 BindException errors)
    throws Exception {
    	String result="Success";
    	String subject = request.getParameter("subject");
    	if ( StringUtils.isBlank(subject)) {
    		subject = "ICN AL FALAH ACADEMY - IMPORTANT INFORMATION";
    	}
    	String mode = request.getParameter("template");
    	if ( "exception".equals(mode) ) {
    		doExceptionEmailing(request);
    	} else {    	
	    	String template = request.getParameter("template");
	    	if ( StringUtils.isBlank(template)) {
	    		template = "parents_passwords.vm";
	    	}
	    	boolean debug = false;
	    	String email = request.getParameter("email");
	    	if ( StringUtils.isBlank(email)) {
	    		debug = false;
	    	} else {
	    		debug = true;
	    	}
	    	
	        if (log.isDebugEnabled()) {
	            log.debug("entering 'onSubmit' method...");
	        }
	        if ( debug )  {
	        	// emails could be csv list
	        	List<String> emails = Arrays.asList(email.split(","));
	        	for (String e1 : emails) {
		            Map model = new HashMap();
		            Person p = personManager.getPersonByEmail(e1);
		            if ( p == null ) {
		            	continue;
		            }
		            if ( p.getParent() != null ) {
		            	p = personManager.getLoadedPerson(p.getParent().getPersonId());
		            } else {
		            	p = personManager.getLoadedPerson(p.getPersonId());
		            }
		            // if this parent has students then email him otherwise continue to next
		            if ( p.getStudents("Student-2014").size() == 0) {
		            	continue;
		            }
		            model.put("number", new NumberTool());
		            model.put("parent", p);
		            model.put("passKey", URLEncoder.encode(new DesEncrypter(Constants.PASS_PHRASE).encrypt(""+p.getPersonId()),"UTF-8"));                    	
		        	result = mailEngine.getConvertedMessage(template, model);
		        	System.out.println("*************");
		        	System.out.println(result);
		        	System.out.println("*************");
		        	try {
		        		mailEngine.sendMimeMessage(
		        				template, 
		        				model, 
		        				StringUtils.isBlank(request.getParameter("from")) ? "admin@icnschool.com": request.getParameter("from"), 
		        				StringUtils.isBlank(request.getParameter("to")) 
		        					? p.getEmails().toArray(new String[]{})
		        					: new String[]{request.getParameter("to")}, 
		        				subject
		        		);
		        	} catch(Exception e) { 
		        		e.printStackTrace();
		        	}
	        	}
	        } else {
		        Role role = lookupManager.getRoleByName("Student-2014");
		        Locale locale = request.getLocale();
		        List<Person> persons = personManager.getParentsWithEmail(role);
		        System.out.println(persons.size());
		        for ( Person p: persons) {
		        	if ( p.getEmails().size() > 0 ) {
		        		sendEmail(p, subject, template);
		        	}
		        }
	        }
    	}
        return new ModelAndView("importReport","result", result);
    }
    
    private void sendEmail(Person p, String subject, String template) {
		try {
            Map model = new HashMap();
            model.put("number", new NumberTool());
            model.put("parent", p);
            model.put("passKey", URLEncoder.encode(new DesEncrypter(Constants.PASS_PHRASE).encrypt(""+p.getPersonId()),"UTF-8"));            
            System.out.println(p.getEmails());
            System.out.println(template);		
        	CommonUtil.send(
        			"admin@icnschool.com", 
        			p.getEmails().toArray(new String[]{}), 
        			null, 
        			subject, 
        			mailEngine.getConvertedMessage(template, model)
        	);
		} catch (Exception e) {
			//e.printStackTrace();
			//System.err.println(e.getMessage());
		}
    }

	private void doExceptionEmailing(HttpServletRequest request) {
        //Role role = lookupManager.getRoleByName("Student-2013");
		// I need to send for different scenarios
		// send all unregistered
		// send all registered but not paid
		// send all partially registered
        Locale locale = request.getLocale();
        // scenario 1 not registered
        List<Person> persons = personManager.getParentsWithEmail(getRoleManager().getRole("Student-2013"));
        List<Person> unRegisteredList = new ArrayList<Person>();
        List<Person> partialRegistered = new ArrayList<Person>();
        for (Person p : persons) {
        	if ( p.getStudents("Student-2014").size() == 0) {
        		unRegisteredList.add(p);
        	} else if ( p.hasUnregisteredStudents("Student-2014","Student-2013") ) {
        		partialRegistered.add(p);
        	}
        }
        System.out.println("unregistered: " + unRegisteredList.size());
        for ( Person p: unRegisteredList ) {
        	if ( p.getEmails().size() > 0 ) {
        		sendEmail(p, "ICN AL FALAH ACADEMY - REGISTRATION" , "unregistered.vm");
        	}
        }
        
        System.out.println("partial: " + partialRegistered.size());
        for ( Person p: partialRegistered ) {
        	if ( p.getEmails().size() > 0 ) {
        		sendEmail(p, "ICN AL FALAH ACADEMY - REGISTRATION" , "partiallyRegistered.vm");
        	}
        }
        
        List<Person> registeredNotPaid = 
        		personManager.getParentsWithEmail(getRoleManager().getRole("Student-2014"));
        System.out.println("totalregistered: " + registeredNotPaid.size());
        int i = 0;
        for (Person p : registeredNotPaid) {
        	if ( 
        				p.getTotalFees("WeekendSchoolFees2014") 
        			+	p.getTotalFees("Payment_Plan_2014")
        			+	p.getTotalFees("TeacherDiscount2014")
        		== 0
        	) {
        		i++;
        		sendEmail(p, "ICN AL FALAH ACADEMY - REGISTRATION", "registeredAndNotPaid.vm");
        	}
        }
        System.out.println("number of registered and not paid: " + i);
        
        
		
	}

	public LookupManager getLookupManager() {
		return lookupManager;
	}

	public void setLookupManager(LookupManager lookupManager) {
		this.lookupManager = lookupManager;
	}

	public MailEngine getMailEngine() {
		return mailEngine;
	}

	public void setMailEngine(MailEngine mailEngine) {
		this.mailEngine = mailEngine;
	}

	public PersonManager getPersonManager() {
		return personManager;
	}

}
